import {
	_decorator,
	Component,
	Node,
	systemEvent,
	EventTouch,
	SystemEvent,
	v3,
	Prefab,
	instantiate,
	Vec3,
	Touch,
	log,
	director,
	Label,
	game,
} from "cc";
import { Menu } from "electron";

import { Ball } from "./Ball";
import { GameState } from "./global/GameState";
import { MyMenu } from "./Menu";
const { ccclass, property } = _decorator;


const BLOCK_NUM = 15;
@ccclass("Game")
export class Game extends Component {
	@property({ type: Node })
	ballNode: Node | null = null;

	@property({ type: Prefab })
	blockPrefab: Prefab | null = null;

	@property({ type: Label })
	label: Label | null = null;

	@property(MyMenu)
	menu:MyMenu|null=null;

	@property
	speed: number = 6;

	blockList: Node[] = [];
	gameState: GameState = GameState.wait;

	onLoad() {
		game.on("game-start", this.startGame, this);
		game.on("game-over", this.gameOver, this);
		
		this.ballNode?.on("collision", this.addScore, this);
	}

	start() {
		systemEvent.on(
			SystemEvent.EventType.TOUCH_START,
			this.onTouchStart,
			this
		);
		this.initBlock();
	}



	onTouchStart(touch: Touch, event: EventTouch) {
		
		let ball = this.ballNode?.getComponent(Ball);
		ball?.boost();
	}

	initBlock() {
		for (let i = 0; i < BLOCK_NUM; i++) {
			let block = instantiate(this.blockPrefab) as Node | null;
			if (block) {
				this.node.addChild(block);
				block?.setPosition(v3(i * 2, 0, 0));
				this.resetBlock(block);
				if(i<3){
					block.setPosition(v3(i * 2, 0, 0));
					block.scale=v3(2,block.scale.y,block.scale.z);
				}
			}
		}
	}

	update(deltaTime: number) {
		if (this.gameState == GameState.start) {
			let flag = false;
			for (let block of this.blockList) {
				let pos = block.getPosition();
				log(deltaTime);
				pos.x -= deltaTime * this.speed;
				block.setPosition(pos);
				if (block.position.x < -8) {
					flag = true;
				}
			}
			if (flag) {
				let pos =
					this.blockList[this.blockList.length - 1].getPosition();
				pos.x += 2+Math.random()-0.5;
				let first = this.blockList.shift();
				if (first) {
					first.setPosition(pos);
					this.resetBlock(first);
				}
			}
		}
	}

	resetBlock(block: Node) {
		let scale = block.scale as Vec3;
		scale.x = Math.random() + 0.5;
		block.scale = scale;

		let pos=block.position as Vec3;
		pos.y=Math.random()-0.5;
		block.position=pos; 

		this.blockList.push(block);
	}

	startGame(){
		if (this.gameState == GameState.wait) {
			this.gameState = GameState.start;
		}
	}

	gameOver() {
		this.gameState = GameState.end;	
		this.menu?.setMaxScore(this.score);
		this.scheduleOnce(() => {
			director.loadScene("game");
		});
	}

	score: number = 0;
	addScore() {
		if (this.gameState == GameState.start) {
			this.score++;
			if (this.label) {
				this.label.string = this.score.toString();
			}
		}
	}
}
